<template>
  <div class="videoBorder" ref="videoBorder">
    <context-menu
      :menu="[{ label: '清屏' }, { label: '进入作者主页' }, { label: '不感兴趣' }, { label: '意见反馈' }, { label: '进入详情页' },{ label: '敬请期待' }]"
      @select="handleSelect">
      <div class="videoBoxPre" ref="videoPrev" data-name="prev">
        <div class="video-function">
          <video-tiplist class="tipList-position" :index="nowPrevIndex"></video-tiplist>
          <div id="mse1"></div>
        </div>
        <comment-infolist v-if="commentStatus" :commentList="preCommentInfo"></comment-infolist>
      </div>
      <div class="videoBoxCur" ref="videoCur" data-name="cur">
        <div class="video-function" ref="videoFunction">
          <video-tiplist class="tipList-position" ref="tipListCur" :index="nowCurIndex"></video-tiplist>
          <div id="mse2"></div>

          <!-- 插入视频介绍 -->
          <div class="video-introduction" ref="introRef">
            <h3>{{ '@' + videoInfoList[nowUrlIndex]?.author_name }}</h3>
            <p>{{ videoInfoList[nowUrlIndex]?.video_title }}</p>
          </div>

          <Barrage :videoDom="player?.video" :data="barrageData" ref="barrageRef" @click="player.video.click()">
          </Barrage>
        </div>
        <comment-infolist v-if="commentStatus" :commentList="nowCommentInfo"
          @send-comment="sendComment"></comment-infolist>
      </div>
      <div class="videoBoxNext" ref="videoNext" data-name="next">
        <div class="video-function">
          <video-tiplist class="tipList-position" :index="nowNextIndex"></video-tiplist>
          <div id="mse3"></div>
        </div>
        <comment-infolist v-if="commentStatus" :commentList="nextCommentInfo"></comment-infolist>
      </div>
    </context-menu>
  </div>
</template>

<script>
import VideoTiplist from '../components/videoTips/index.vue'
import ContextMenu from '@/components/contextMenu/index.vue'
import Player from 'xgplayer'
import 'xgplayer/dist/index.min.css'
import VideoTip from '@/components/videoTips/components/VideoTip.vue'
import CommentInfolist from '@/components/commentVideo/index.vue'
import Barrage from '@/components/barrage/v_common/index.vue'
import { inputPlugin } from '@/plugins/xgplayer.js'
import { Events } from 'xgplayer'
import api from '@/api/axios.js'
import { ElMessage } from 'element-plus'

export default {
  components: { VideoTip, VideoTiplist, CommentInfolist, ContextMenu, Barrage },
  name:'Recommend',
  data() {
    return {
      id:'mse1',
      urlList: [],
      nowPrevIndex: 0,
      nowUrlIndex: 0,
      nowCurIndex: 0,
      nowNextIndex: 0,
      player: null, //实例
      IsTransition: false,
      preCommentInfo: [],
      nextCommentInfo: [],
      barrageData: []
    }
  },
  computed: {
    videoInfoList: {
      get() { return this.$store.state.videoFunctionList.videoInfoList },
      set(val) { this.$store.commit('videoFunctionList/initVideoListInfo', val) }
    },
    nowCommentInfo: {
      get() { return this.$store.state.videoFunctionList.nowCommentInfo },
      set(val) { this.$store.commit('videoFunctionList/initVideoCurComment', val) }
    },
    commentStatus: {
      get() { return this.$store.state.videoFunctionList.commentStatus }
    },
    user: {
      get() {
        return {
          user_id: this.$store.state.user.user_id,
          author_name: this.$store.state.user.author_name,
          avatar_url: this.$store.state.user.avatar_url || ''
        } 
      }
    }
  },
  watch: {
    nowUrlIndex() {
      this.$store.commit('videoFunctionList/initVideoListIndex', this.nowUrlIndex)
    }
  },
  mounted() {
    api.getVideoList().then((response) => {
      console.log(response);
      if (response.data.code === '200') {
        this.videoInfoList = response.data.data
        this.getCommentInfo(this.videoInfoList[this.nowUrlIndex].video_id)
        this.urlList = this.videoInfoList.map(item => item.video_url)
        this.creatScroll_Img(this.nowUrlIndex)
      }
    }).catch(function (error) {
      // 请求失败处理
      console.log(error);
    })
    this.$refs.videoFunction.addEventListener('wheel', (e) => {
      if (this.IsTransition === true) return;
      this.IsTransition = true;
      // 记录视频时长
      api.recordHistory({
        video_id: this.videoInfoList[this.nowUrlIndex].video_id,
        watch_duration: this.player?.video.currentTime
      })
      if (e.deltaY < 0) {
        this.nowUrlIndex--;
        if (this.nowUrlIndex < 0) this.nowUrlIndex = this.urlList.length - 1;
        this.scroll_Img(this.$refs.videoPrev, this.$refs.videoCur);
      }
      if (e.deltaY > 0) {
        this.nowUrlIndex = (this.nowUrlIndex + 1) % this.urlList.length;
        this.scroll_Img(this.$refs.videoNext, this.$refs.videoCur);
      }
    });
  },
  methods:{
    handleSelect(val) {
      this.$message.open({
        tittle: val.label,
        type: 'success',
        duration: 1000,
        center: true
      })
    },
    // 根据当前视频id获取相应评论信息,以及是否点赞收藏
    async getCommentInfo(id, type) {
      try {
        const videoInfo = this.videoInfoList.find(it => it.video_id === id)
        api.getComment(id).then(response => {
          if (response.data.code === '200') {
            this.nowCommentInfo = response.data.data
            this.videoDescription = response.data.data.description
          }
        })
        api.getLikeStatus({
          video_id: id
        }).then(response => {
          videoInfo.loveStatus = response.data.data.isLiked
          // console.log(response)
        })
        api.getCollectionStatus({
          video_id: id
        }).then(response => {
          videoInfo.collectStatus = response.data.data.isCollected
          // console.log(response)
        })
      }
      catch(error) {
        // 请求失败处理
        console.log(error)
      }
    },
    initPlayer(id,url) {
      let _this = this;
      if (!url) return console.warn("url is not esist");
      const config = {
        lang: 'zh',
        id: id,
        url: url,
        plugins: [inputPlugin], 
        width: '100%',
        height: '100%',
        loop: true,
        volume: 0.3,
        // playsinline: true,
        // 进度条true为不显示
        // isLive: true,
        /**倍速播放 */
        playbackRate: [0.5, 0.75, 1, 1.5, 2],
        defaultPlaybackRate: 1,
        download: true,
        commonStyle: {
          // 播放完成部分进度条底色
          playedColor: 'rgba(255, 255, 255, 0.7)',
        },
        miniprogress: true,
        dynamicBg: {
          disable: false,
          mode: 'firstframe'
        },
        playsinline: this.isAppleDevice(), // IOS设备设置，防止被浏览器劫持
        "x5-video-player-type": "h5", // 微信内置浏览器设置，防止被浏览器劫持
        "x5-video-orientation": "portraint",
        /**画中画 */
        pip: false,
        thumbnail: {
          height: 25,
        },
        pipConfig: {
          bottom: 0,
          right: 0,
          width: 320,
          height: 80,
        },
        // download: true,
        /**初始化首帧 */
        videoInit: true,
        autoplay: id === 'mse2' ? true : false,
        // 静音播放
        // autoplayMuted: false,
        // 截图功能跨域用不了
        // screenShot: {
        //   saveImg: true,
        //   quality: 0.92,
        //   type: "image/png",
        //   format: ".png",
        // },
        // 菜单控件
        controlPlugins: [],
      };
      //========================== 2，开始实例化======================
      const player = new Player(config);

      if (player) {
        // player.getCssFullscreen()
        //
        // setTimeout(()=>{
        //   player.exitCssFullscreen()
        // },5000)
        /* 这里注册监听 */
        // player.once('complete', () => {
        //   console.log('complete')
        //   try {
        //     player.play() // 尝试再次执行播放
        //     setTimeout(() => { // 500毫秒收检测
        //       if (!player.hasStart && player.currentTime ===
        //           0) { // hasStart返回false，并且播放时间还是0，那么就可以认为自动播放失效了
        //
        //       }
        //     }, 500)
        //   } catch (e) {
        //     console.log(e);
        //   }
        // });
        // 输入弹幕插件
        const inputPlugin = player.getPlugin('inputPlugin')
        inputPlugin.buttonDom.onclick = () => {
          this.addDanmaku(inputPlugin)
        }
        inputPlugin.root.onclick = () => {}
        // 监听视频开始播放 播放传给父组件的是true
        player.on("play", () => {
          this.$emit("triggerEvent", true);
        });
        // 监听视频已经暂停 暂停传给父组件的是true
        player.on("pause", () => {
          this.$emit("triggerEvent", false);
        });
        // 视频加载失败，报错误提示
        player.on("error", () => {
          console.log("视频加载错误，请确认视频地址后再连接!");
          //this.$message.warning('视频加载错误，请确认视频地址后再连接!');
        });
        player.addClass('className7777777')
        // 监听 视频退出全屏
        // player.on('exitFullscreen', () => {
        //   window.scrollTo(0, 0);
        //   console.log('已经退出全屏了');
        // });

        //检测画面是否卡死。如果decodedFrames不再发生变化,就销毁掉该实例并进行重新连接。
        // player.on("statistics_info", function (res) {
        //   if (_this.lastDecodedFrame == 0) {
        //     _this.lastDecodedFrame = res.decodedFrames;
        //     return;
        //   }
        //   if (_this.lastDecodedFrame != res.decodedFrames) {
        //     _this.lastDecodedFrame = res.decodedFrames;
        //     _this.sameCount = 0;
        //   } else {
        //     _this.sameCount++;
        //     console.log(
        //       "decodedFrames没有发生变化第",
        //       _this.sameCount,
        //       "次。时间：",
        //       new Date()
        //     );

        //     if (_this.sameCount > 9) {
        //       //decodedFrames10秒不变，则判断为画面卡死，销毁实例进行重连
        //       console.log(
        //         "画面卡死，进行重连————————player:",
        //         _this.player,
        //         ".时间",
        //         new Date()
        //       );
        //       //重置变量
        //       _this.lastDecodedFrame = 0;
        //       _this.sameCount = 0;

        //       if (_this.player) {
        //         _this.player.destroy(); //销毁
        //         _this.getData(); //重连
        //         console.log("重连完毕");
        //       }
        //     }
        //   }
        // });
      }

      return player
    },
    // IOS设备设置，防止被浏览器劫持
    isAppleDevice() {
      const ua = navigator.userAgent.toLowerCase();
      return /iphone|ipad|phone|Mac/i.test(ua);
    },
    creatScroll_Img(curIndex) {
      this.nowPrevIndex = curIndex === 0 ? this.urlList.length - 1 : curIndex - 1;
      this.nowNextIndex = curIndex === this.urlList.length - 1 ? 0 : curIndex + 1;
      this.nowCurIndex = curIndex
      this.$refs.barrageRef.clearBarrage()
      this.barrageData = this.getBarrageData(curIndex)
      this.initPlayer('mse1', this.urlList[this.nowPrevIndex])
      this.player = this.initPlayer('mse2', this.urlList[curIndex])
      this.player.on(Events.COMPLETE, () => {
        // console.log('complete')
        this.player.root.appendChild(this.$refs.barrageRef.$el)
        this.player.root.appendChild(this.$refs.introRef)
      })
      this.player.on(Events.VIDEO_RESIZE, () => {
        // console.log('video_resize')
        if (this.$refs.barrageRef) this.$refs.barrageRef.init()
      })
      this.player.on(Events.PLAY, () => {
        this.$refs.barrageRef.playBarrage()
      })
      this.player.on(Events.PAUSE, () => {
        if (this.$refs.barrageRef) this.$refs.barrageRef.pauseBarrage()
      })
      this.player.on(Events.SEEKING, () => {
        console.log('SEEKING')
        this.barrageData = this.getBarrageData(curIndex)
        // seek前执行，也就是SEEKING，因为弹幕还在运行，不然就会一下子把小于当前时间的所有弹幕渲染出来
        this.$refs.barrageRef.openFilter()
      })
      this.initPlayer('mse3', this.urlList[this.nowNextIndex])
      this.getCommentInfo(this.videoInfoList[this.nowUrlIndex].video_id)
    },
    scroll_Img(PrevOrNxet, cur) {
      PrevOrNxet.style.transition = 'height 1s';
      PrevOrNxet.style.height = '100%';
      cur.style.transition = 'transform 1s';
      cur.style.transform = PrevOrNxet.dataset.name === "prev" ? `translateY(20%)` : `translateY(-20%)`;
      setTimeout(() => {
        PrevOrNxet.style.transition = 'none';
        cur.style.transition = 'none';
        cur.style.transform = `translateY(0)`;
        PrevOrNxet.style.height = '0';
        PrevOrNxet.offsetWidth; //强制渲染
        this.creatScroll_Img(this.nowUrlIndex)
        this.IsTransition = false;
      }, 1000);
    },
    getBarrageData(curIndex){
      return this.videoInfoList[curIndex].danmaku_list.map(item => {
        return {
          value: item.content,
          fontSize: item.font_size,
          color: item.color,
          time: item.time_point,
          speed: 3,
          key: item.id
        }
      })
    },
    async addDanmaku(that) {
      const inputValue = that.inputDom.value
      const videoInfo = this.videoInfoList[this.nowUrlIndex]
      if (inputValue.trim()) {
        // 这里可以添加发送弹幕的具体逻辑
        const danmu = {
          video_id: videoInfo.video_id,
          content: that.inputDom.value,
          time_point: this.player?.video.currentTime,
          color: '#ff0000',  // 红色
          font_size: 30      // 大号字体
        }
        const { data: { data } } = await api.addDanmaku(danmu)
        ElMessage({
          message: '发送弹幕成功!',
          type: 'success',
        })
        // console.log('data', data)
        this.$refs.barrageRef.addBarrage({
          value: data.content,
          fontSize: data.font_size,
          color: data.color,
          time: data.time_point,
          speed: 3,
          key: data.danmaku_id
        })
        that.inputDom.value = '' // 清空输入框
      }
    },
    async sendComment(comment) {
      try {
        const videoInfo = this.videoInfoList[this.nowUrlIndex]
        this.nowCommentInfo.unshift({
          comment_info: comment,
          comment_time: new Date(),
          comment_userName: this.user.author_name,
          video_id: videoInfo.video_id,
          avatar_url: this.user.avatar_url
        })
        this.videoInfoList[this.nowUrlIndex].comment_num++
        await api.addComment({
          content: comment,
          parent_id: 0,
          video_id: videoInfo.video_id
        })
        ElMessage.success('发送评论成功')
      } catch (error) {
        ElMessage.error('发送评论失败')
      }
    }
  }
}
</script>

<style scoped>
.videoBorder {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 20px;
  overflow: hidden;
}
.videoBoxPre {
  display: flex;
  overflow: hidden;
  position: absolute;
  top: 0;
  width: 100%;
  height: 0;
  z-index: 1;
}
.videoBoxNext {
  display: flex;
  overflow: hidden;
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 0;
  z-index: 1;
}
.videoBoxCur {
  display: flex;
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
}
.video-function {
  position: relative;
  width: 100%;
  height: 100%;
}
.tipList-position {
  position: absolute;
  z-index: 10;
  top: 25%;
  right: 10px;
}
.video-introduction {
  position: absolute;
  z-index: 10;
  bottom: 50px;
  left: 15px;
  padding: 15px;
  border-radius: 10px; /* 圆角 */
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  transition: transform 0.3s ease; /* 动画效果 */
}

.video-introduction:hover {
  transform: scale(1.02); /* 悬停时放大 */
}

.video-introduction h3 {
  margin: 0;
  font-size: 20px; /* 标题字体大小 */
  color: #ffffff; /* 标题颜色 */
  font-weight: bold; /* 加粗 */
}

.video-introduction p {
  margin: 5px 0 0;
  font-size: 16px; /* 描述字体大小 */
  color: #d3cfcf; /* 描述颜色 */
  line-height: 1.5; /* 行高 */
}
</style>